package org.lookouster.nextAgadir.pointageBureau.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import org.lookouster.nextAgadir.pointageBureau.bases.Billon;
import org.lookouster.nextAgadir.pointageBureau.bases.Controle;
import org.lookouster.nextAgadir.pointageBureau.bases.Controleur;
import org.lookouster.nextAgadir.pointageBureau.bases.EspaceTravail;
import org.lookouster.nextAgadir.pointageBureau.bases.Ferme;
import org.lookouster.nextAgadir.pointageBureau.bases.Secteur;
import org.lookouster.nextAgadir.pointageBureau.bases.Serre;
import org.lookouster.nextAgadir.pointageBureau.outils.BDConnect;
import org.lookouster.nextAgadir.pointageBureau.outils.BDFunctions;
/*
 * RechercheChamp.java
 *
 * Created on 25 avril 2008, 03:16
 */
import org.lookouster.nextAgadir.pointageBureau.outils.functions;


/**
 *
 * @author  Lookouster
 */
public class PlanControle extends javax.swing.JDialog {
	
	// Variables declaration - do not modify                     
    private javax.swing.JButton moveBtn;
    private javax.swing.JButton removeBtn;
    private javax.swing.JButton saveBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lblValidite;
    private javax.swing.JList listCtl;
    private javax.swing.JList listCtlSel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTree listChamps;
    private Map<Integer,TreePath> allPathsIndexes=null;//Integer->champId
    private List<Controleur> allControleurs=null;
    private List<Controleur> selControleurs=null;
    private List<Controle> controles=null;
    private Date date;
    // End of variables declaration     
    
    /** Creates new form RechercheChamp */
    public PlanControle(java.awt.Frame parent, Date d, boolean modal) {
        super(parent, modal);
        //System.out.println("from my class: "+d);
        date=d;
        initComponents();
        //System.out.println("from my class date: "+date);
    }
    
                           
    private void initComponents() {
    	
    	
    	allControleurs=BDFunctions.getControleurList();
    	selControleurs=new ArrayList<Controleur>();
    	
    	DefaultMutableTreeNode top =
            new DefaultMutableTreeNode(UICommons.chp);
        createNodes(top);
    	
    	setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        jScrollPane1 = new javax.swing.JScrollPane();
        listChamps = new javax.swing.JTree(top);
        jLabel1 = new javax.swing.JLabel(UICommons.flblPlanCtlTitle);
        jScrollPane2 = new javax.swing.JScrollPane();
        listCtl = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel(UICommons.flblPlanCtlListCtl);
        jLabel3 = new javax.swing.JLabel();
        lblValidite=new javax.swing.JLabel(UICommons.flblValid+date);
        moveBtn = new javax.swing.JButton(UICommons.btnMove);
        jScrollPane3 = new javax.swing.JScrollPane();
        listCtlSel = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel(UICommons.flblPlanCtlOpt);
        controles=new ArrayList<Controle>();
        removeBtn=new JButton(UICommons.btnRemove);
        saveBtn=new JButton(UICommons.btnValid);
        
        reloadListControleurs();
        
        /*listChamps.getSelectionModel().setSelectionMode(
        		TreeSelectionModel.SINGLE_TREE_SELECTION);*/
        listCtl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        listCtlSel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        listCtlSel.addListSelectionListener(new ListSelectionListener()
        {

			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				// TODO Auto-generated method stub
				selectCorrespondingChamps();
			}
        	
        });
        
        moveBtn.addActionListener(new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				moveControleur();
			}
        	
        });
        
        removeBtn.addActionListener(new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				removeControleur();
			}
        	
        });
        
        saveBtn.addActionListener(new ActionListener()
        {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				saveThatControle();
			}
        	
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        
        jScrollPane1.setViewportView(listChamps);

        
        /*listCtl.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });*/
 
        jScrollPane2.setViewportView(listCtl);

       
        /*listCtlSel.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });*/
 
        jScrollPane3.setViewportView(listCtlSel);



        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(lblValidite, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(66, 66, 66)
                        .addComponent(jLabel3)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(63, 63, 63)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(saveBtn)
                                    .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(41, 41, 41)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                     .addComponent(removeBtn, 0, 0, Short.MAX_VALUE)
                                     .addComponent(moveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(48, 48, 48)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addContainerGap(63, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 157, Short.MAX_VALUE)
                        .addComponent(jLabel4)
                        .addGap(207, 207, 207))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(205, Short.MAX_VALUE)
                .addComponent(removeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(moveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(188, 188, 188))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        		.addComponent(saveBtn)
                        		 .addComponent(lblValidite))
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE))
                .addGap(12, 12, 12))
        );

        pack();
    }                     
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PlanControle dialog = new PlanControle(new javax.swing.JFrame(),
                		new Date(108, 5, 25),true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    
    public void createNodes(DefaultMutableTreeNode top) {

        
        DefaultMutableTreeNode fermes=null;
        DefaultMutableTreeNode serres=null;
        DefaultMutableTreeNode secteurs=null;
        DefaultMutableTreeNode billons=null;
        
        List<Ferme> lesFermes;
        List<Serre> lesSerres;
        List<Secteur> lesSecteurs;
        List<Billon> lesBillons;
        allPathsIndexes=new HashMap<Integer, TreePath>();
		try {
			lesFermes = BDFunctions.getFermesList();
			if(lesFermes!=null)
			{
				BDConnect bdc=new BDConnect();
				for(Ferme f:lesFermes)
		        {
		        	fermes=new DefaultMutableTreeNode(f);
		        	allPathsIndexes.put(f.getIdEspaceTravail(),
		        			new TreePath(fermes.getPath()));
		        	top.add(fermes);
		        	
		        	if(f.getSecteurs()!=null)
		        	{
		        		lesSecteurs=new ArrayList<Secteur>(f.getSecteurs());
		        		for(Secteur st:lesSecteurs)
			        	{
			        		secteurs=new DefaultMutableTreeNode(st);
			        		
			        		fermes.add(secteurs);
			        		
			        		allPathsIndexes.put(st.getIdEspaceTravail(),
				        			new TreePath(secteurs.getPath()));
			        		
			    
			        		if(st.getSerres()!=null)
			        		{
			        			lesSerres=new ArrayList<Serre>(st.getSerres());
			        			for(Serre sr:lesSerres)
				        		{
				        			serres=new DefaultMutableTreeNode(sr);
				        			
				        			secteurs.add(serres);
				        			
				        			allPathsIndexes.put(sr.getIdEspaceTravail(),
						        			new TreePath(serres.getPath()));
				        			
				        			if(sr.getBillons()!=null)
				        			{
				        				lesBillons=new ArrayList<Billon>(sr.getBillons());
					        			
				        				for(Billon b:lesBillons)
					        			{
					        				billons=new DefaultMutableTreeNode(b);
					        				
					        				serres.add(billons);
					        				
					        				allPathsIndexes.put(b.getIdEspaceTravail(),
					    		        			new TreePath(billons.getPath()));
					        			}
					        			//functions.affiche(st.getNomEspaceTravail());
				        			}
				        			
				        			
				        			
				        		}
			        		}
			        		
			        	}
		        	}
		        	
		        	
		        }
				bdc.shutdown();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			functions.affiche("pb populatin champ Tree: "+e.getMessage());
		}
    }
    
    
    public void reloadListControleurs()
    {
    	
    	if(allControleurs.isEmpty())
    	{
    		listCtl.setModel(new DefaultListModel());
    		return;
    	}
    	listCtl.setModel(new ListModel()
    	{

			@Override
			public void addListDataListener(ListDataListener arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public Object getElementAt(int arg0) {
				// TODO Auto-generated method stub
				return allControleurs.get(arg0).getMatriculeEmploye();
			}

			@Override
			public int getSize() {
				// TODO Auto-generated method stub
				return allControleurs.size();
			}

			@Override
			public void removeListDataListener(ListDataListener arg0) {
				// TODO Auto-generated method stub
				
			}
    		
    	});
    }
    
    
    public void moveControleur()
    {
    	
    	TreePath[] selection=listChamps.getSelectionPaths();
    	if(selection==null || listCtl.getSelectedIndex()==-1)
    	{
    		JOptionPane.showMessageDialog(this,UICommons.selCtlChps);
    		return;
    	}
    	List<EspaceTravail> champsCtl=new ArrayList<EspaceTravail>();
    	for(int i=0;i<selection.length;i++)
    		champsCtl.add((EspaceTravail)((DefaultMutableTreeNode)selection[i].getLastPathComponent()).getUserObject());
    	controles.add(new Controle(allControleurs.get(listCtl.getSelectedIndex()),champsCtl));
    	
    	selControleurs.add(allControleurs.get(listCtl.getSelectedIndex()));
    	allControleurs.remove(listCtl.getSelectedIndex());
    	
    	reloadListControleurs();
    	reloadListSelControleurs();
    	
    }
    
    public void removeControleur()
    {
    	if(listCtlSel.getSelectedIndices().length==0)
    	{
    		JOptionPane.showMessageDialog(this,UICommons.selCtl);
    		return;
    	}
    	List<Controleur> toBeRemoved=new ArrayList<Controleur>();
    	for(int i=0;i<listCtlSel.getSelectedIndices().length;i++)
    	{
    		allControleurs.add(selControleurs.get(i));
    		toBeRemoved.add(selControleurs.get(i));
    		controles.remove(i);
    	}
    	selControleurs.removeAll(toBeRemoved);
    	reloadListControleurs();
    	reloadListSelControleurs();
    		
    }
    
    
    
    /**
     * Reload List Selected Controleurs for Controle UI side
     */
    public void reloadListSelControleurs()
    {
    	if(selControleurs.isEmpty())
    	{
    		listCtlSel.setModel(new DefaultListModel());
    		return;
    	}
    	listCtlSel.setModel(new ListModel()
    	{

			@Override
			public void addListDataListener(ListDataListener l) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public Object getElementAt(int index) {
				// TODO Auto-generated method stub
				return selControleurs.get(index).getMatriculeEmploye();
			}

			@Override
			public int getSize() {
				// TODO Auto-generated method stub
				return selControleurs.size();
			}

			@Override
			public void removeListDataListener(ListDataListener l) {
				// TODO Auto-generated method stub
				
			}
    		
    	});
    }
    
    
    void selectCorrespondingChamps()
    {
    	//functions.affiche("selection!!");
    	if(listCtlSel.getSelectedIndex()==-1)
    	{
    		listChamps.setSelectionPaths(null);
    		return;
    	}
    	List<EspaceTravail> tmpChamps=new ArrayList<EspaceTravail>(
    			controles.get(listCtlSel.getSelectedIndex()).getEspaceTravail());
    	int nbPath=tmpChamps.size();
    	//System.out.println(nbPath);
    	TreePath[] selectedPaths=new TreePath[nbPath];
    	for(int i=0;i<nbPath;i++)
    		selectedPaths[i]=allPathsIndexes.get(tmpChamps.get(i).getIdEspaceTravail());
    	//functions.affiche(selectedPaths[0].toString());
    	listChamps.setSelectionPaths(selectedPaths);
    	
    }
    
    
    void saveThatControle()
    {
    	if(selControleurs.isEmpty())
    	{
    		JOptionPane.showMessageDialog(this, UICommons.emptyCtl);
    		return;
    	}
    	BDConnect bdc;
		try {
			bdc = new BDConnect();
			for(Controle c:controles)
			{
				c.setDateControle(date);
	    		c.saveDB(bdc);
			}
	    	bdc.shutdown();
	    	JOptionPane.showMessageDialog(this, UICommons.notifSaveSuccess);
	    	this.setVisible(false);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			functions.affiche("pb saving controle: "+e.getMessage());
		}
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}

